package com.xian.ucenter.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xian.ucenter.entities.PostTag;
import com.xian.ucenter.entities.Tag;
import com.xian.ucenter.entities.vo.TagNames;
import com.xian.ucenter.mapper.TagMapper;
import com.xian.ucenter.service.PostTagService;
import com.xian.ucenter.service.TagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 标签管理表 服务实现类
 * </p>
 *
 * @author xian
 * @since 2022/07/23 02:59
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private PostTagService postTagService;
    @Override
    public Long queryPostCountByTagId(String id) {
        return postTagService.count(new QueryWrapper<PostTag>().eq("tag_id",id));
    }

    @Override
    public List<TagNames> getTagList() {
        return BeanUtil.copyToList(list(), TagNames.class);
    }

    @Override
    public List<String> getTagIdsByPostId(String id) {
        QueryWrapper<PostTag> postTagQueryWrapper = new QueryWrapper<>();
        postTagQueryWrapper.eq("post_id",id);
        List<PostTag> list = postTagService.list(postTagQueryWrapper);
        if (ObjectUtil.isNotNull(list) && list.size() > 0) {
            return list.stream().map(PostTag::getTagId).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<String> getTagNamesByPostId(String id) {
        QueryWrapper<PostTag> postTagQueryWrapper = new QueryWrapper<>();
        postTagQueryWrapper.eq("post_id",id);
        List<PostTag> list = postTagService.list(postTagQueryWrapper);
        if (ObjectUtil.isNotNull(list) && list.size() > 0) {
            List<String> collect = list.stream().map(PostTag::getTagId).collect(Collectors.toList());
            return listByIds(collect).stream().map(Tag::getTagName).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<Tag> getTagByPostId(String id) {
        List<PostTag> postTags = postTagService.list(new QueryWrapper<PostTag>().eq("post_id", id));
        List<Tag> tags = null;
        if (ObjectUtil.isNotNull(postTags) && postTags.size() > 0) {
            tags = listByIds(postTags.stream().map(PostTag::getTagId).collect(Collectors.toList()));
        }

        return tags;
    }
}
